package com.mxcyk.plug.notbook;

import java.awt.BorderLayout;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;

/**
 * 功能：简易记事本
 * Java右键菜单实现文本组件内容的的复制、粘贴、剪切功能
 * 
 */

public class Notbook extends JPanel {

	private JScrollPane pane = null;
	private TextAreaMenu text = null;
	private JPanel jp;
	JScrollPane scroll=null;
	public Notbook() {
		text = new TextAreaMenu();
		scroll=new JScrollPane(text);
		//scroll.setHorizontalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);//水平不显示
		scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);//垂直根据需要显示
		this.setLayout(new BorderLayout());
		this.add(scroll);
		
	}

	public static void main(String args[]) {
		JFrame jf=new JFrame("记事本测试");
		jf.setSize(300,400);
		jf.add(new Notbook());
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		jf.setVisible(true);
	}
}

/**
 * 带有功能菜单的JTextArea
 * 
 */
class TextAreaMenu extends JTextArea implements MouseListener {
	private JPopupMenu pop = null; // 弹出菜单
	private JMenuItem save_as = null,newfile=null,open=null; // 功能菜单
	private JMenuItem copy = null, paste = null, cut = null; 

	public TextAreaMenu() {
		super();
		this.setLineWrap(true);//自动换行
		this.setWrapStyleWord(true);//激活断行不断字功能
		init();
	}

	private void init() {
		this.addMouseListener(this);
		pop = new JPopupMenu();
		
		pop.add(open = new JMenuItem("打开"));
		pop.add(save_as = new JMenuItem("另存为"));
		pop.add(newfile = new JMenuItem("新建"));
		pop.add(copy = new JMenuItem("复制"));
		pop.add(paste = new JMenuItem("粘贴"));
		pop.add(cut = new JMenuItem("剪切"));
		
		save_as.setAccelerator(KeyStroke.getKeyStroke('A',
				InputEvent.CTRL_MASK));
		open.setAccelerator(KeyStroke.getKeyStroke('O',
				InputEvent.CTRL_MASK));
		newfile.setAccelerator(KeyStroke.getKeyStroke('N',
				InputEvent.CTRL_MASK));
		copy.setAccelerator(KeyStroke.getKeyStroke('C',
				InputEvent.CTRL_MASK));
		paste.setAccelerator(KeyStroke.getKeyStroke('V',
				InputEvent.CTRL_MASK));
		cut.setAccelerator(KeyStroke
				.getKeyStroke('X', InputEvent.CTRL_MASK));
	
		save_as.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				action(e);
			}
		});
		open.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				action(e);
			}
		});
		newfile.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				action(e);
			}
		});
		
		copy.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				action(e);
			}
		});
		paste.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				action(e);
			}
		});
		cut.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				action(e);
			}
		});
		this.add(pop);
	}

	/**
	 * 菜单动作
	 * 
	 * @param e
	 */
	public void action(ActionEvent e) {
		String str = e.getActionCommand();
		System.out.println(""+str);
		if (str.equals(copy.getText())) { // 复制
			this.copy();
		} else if (str.equals(paste.getText())) { // 粘贴
			this.paste();
		} else if (str.equals(cut.getText())) { // 剪切
			this.cut();
		}else if(str.equals(save_as.getText())){//另存为
			saveFile();
		}else if(str.equals(newfile.getText())){//新建
			this.setText("");
		}else if(str.equals(open.getText())){//打开
			openfile();
			
		}
	}
	//打开文件
	private void  openfile(){
		//这里使用能文件选择组件JFileChooser
		JFileChooser jfc1=new JFileChooser();
		jfc1.setDialogTitle("请选择文件……");
		jfc1.showOpenDialog(null);
		jfc1.setVisible(true);
		//获得文件的绝对路径
		String filename=jfc1.getSelectedFile().getAbsolutePath();
		//System.out.print(filename);

		FileReader readIn = null;
	
		try {
			//---------------------------------------------------------
			//读取文件
			File readFile =new File(filename);
			readIn=new FileReader(readFile);
			int size=(int)readFile.length();
			int charsRead=0;
			char[]content=new char[size];
			while(readIn.ready()){
				charsRead+=readIn.read(content,charsRead,size-charsRead);
			}
			
			this.setText(new String(content,0,charsRead));//显示文件
			//===========================================================
			
		} catch (Exception e2) {
			// TODO: handle exception
			e2.printStackTrace();
			System.out.println("文件打开失败");
		}finally{
			
			try {
				readIn.close();
			} catch (Exception e3) {
				// TODO: handle exception
				System.out.println("记事本文件关闭出错");
			}
		}
	}

	
	private void saveFile() {
		JFileChooser jfc = new JFileChooser();
		jfc.setDialogTitle("另存为");
		int result=jfc.showSaveDialog(null);
		jfc.setVisible(true);
		//如果点击取消按钮
		if(result!=JFileChooser.APPROVE_OPTION){
			return ;
		}
		String file = jfc.getSelectedFile().getAbsolutePath();// 得到用户保存文件的全路径
		//System.out.println("推出是的文件路径"+file);
		// 准备写入到指定文件
		FileWriter fw = null;
		BufferedWriter bw = null;
		try {
			fw = new FileWriter(file);
			bw = new BufferedWriter(fw);
			// 一次性写入到文件如果为打文件就会卡 需做缓存优化
			bw.write(this.getText());
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, e.toString(), "写入文件失败",
					JOptionPane.ERROR_MESSAGE);
			e.printStackTrace();
			// TODO: handle exception
		} finally {
			try {
				bw.close();
				fw.close();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	}


	public JPopupMenu getPop() {
		return pop;
	}

	public void setPop(JPopupMenu pop) {
		this.pop = pop;
	}

	/**
	 * 剪切板中是否有文本数据可供粘贴
	 * 
	 * @return true为有文本数据
	 */
	public boolean isClipboardString() {
		boolean b = false;
		Clipboard clipboard = this.getToolkit().getSystemClipboard();
		Transferable content = clipboard.getContents(this);
		try {
			if (content.getTransferData(DataFlavor.stringFlavor) instanceof String) {
				b = true;
			}
		} catch (Exception e) {
		}
		return b;
	}

	/**
	 * 文本组件中是否具备复制的条件
	 * 
	 * @return true为具备
	 */
	public boolean isCanCopy() {
		boolean b = false;
		int start = this.getSelectionStart();
		int end = this.getSelectionEnd();
		if (start != end)
			b = true;
		return b;
	}

	public void mouseClicked(MouseEvent e) {
	}

	public void mouseEntered(MouseEvent e) {
	}

	public void mouseExited(MouseEvent e) {
	}

	public void mousePressed(MouseEvent e) {
		if (e.getButton() == MouseEvent.BUTTON3) {
			copy.setEnabled(isCanCopy());
			paste.setEnabled(isClipboardString());
			cut.setEnabled(isCanCopy());
			pop.show(this, e.getX(), e.getY());
		}
	}

	public void mouseReleased(MouseEvent e) {
	}

}
